const mongoose = require('mongoose')
const Schema = mongoose.Schema

const bookSchema = new Schema({
  title: {
    type: String,
    required: true,
    trim: true,
    unique: true
  },
  filename: {
    type: String,
    required: true,
    trim: true,
    unique: true
  },
  file_path: {
    type: String,
    required: true,
    trim: true,
    unique: true
  },
  cover_path: {
    type: String,
    required: true,
    trim: true,
    unique: true
  },
  recommend: {
    type: Boolean,
    default: false
  },
  author: String,
  category: String,
  description: String,
  rank: Number,
  created_at: Date,
  updated_at: Date
})

bookSchema.pre('save', function (next) {
  const book = this
  if (!book.isModified || !book.isNew) {
    next()
  } else {
    const currentDate = new Date()
    book.updated_at = currentDate
    if (!book.created_at)
      book.created_at = currentDate
    next()
  }
})

module.exports = mongoose.model('Book', bookSchema)
